import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

class MyTimer {
    //定时器模拟实现
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public MyTimer() {
        //启动线程执行任务
        Thread t = new Thread(() -> {
            while(true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        if(task.getTime() > System.currentTimeMillis()) {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                            //不能使用 while 避免出现更短时间的任务未被执行的情况
                        } else {
                            queue.poll();
                            task.getTask().run();
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }

    public void schedule(Runnable task, long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(task, delay + System.currentTimeMillis());
            queue.offer(myTimerTask);
            locker.notify();//唤醒第一个 wait
        }
    }
}

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    public Runnable getTask() {
        return task;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

public class Demo1 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },10000);
    }
}
